using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class CursorMove : MonoBehaviour
{
    public static float speed = 1;
    public float mm = 100;
    public static Vector3 spawn = Vector3.zero;
    public GameObject canvas;
    public GameObject cam;

    protected static int st;

    public static bool isDead = false;
    public static int gas = 0;

    private Rigidbody2D rb;
    private SpriteRenderer sr;
    private CinemachineBrain ccb;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        ccb = cam.GetComponent<CinemachineBrain>();
    }

    private void Update()
    {
        // Go to spawn
        if (Input.GetMouseButton(0) && Input.GetMouseButton(1))
        {
            st = 5;
            ToSpawn();
        }

        // Sprite
        Color c;
        if (isDead)
        {
            c = Color.red;
        }
        else
        {
            c = new Color(1 - gas / 255f, 1, 1 - gas / 255f, 1);
        }
        sr.color = c;
        /*
        sr.sprite = isDead ? r : w;
        sr.color = isDead ? Color.white :
            new Color(1 - gas / 255f, 1, 1 - gas / 255f, 1);
        */

        // Lock
        Cursor.lockState = !(Input.GetKey(KeyCode.LeftAlt) || Input.GetMouseButton(2))
            ? CursorLockMode.Locked : CursorLockMode.None;

        // speed
        if (Input.GetKey(KeyCode.UpArrow)) speed += 10e-3f;
        else if (Input.GetKey(KeyCode.DownArrow)) speed -= 10e-3f;
    }

    private void FixedUpdate()
    {
        ToSpawn();

        if (isDead) return;

        Vector3 delta = new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0);
        if (Input.GetKey(KeyCode.LeftAlt)) delta = Vector3.zero;

        //transform.position += delta * speed;
        rb.MovePosition(transform.position + delta * speed);

        if (gas > 0) gas -= 5;

        if (gas >= 255) GoDead();
    }

    private void ToSpawn()
    {
        if (st == 5)
        {

            gas = 0;
            SceneManager.LoadScene(0);
            ccb.enabled = false;
            isDead = false;
        }

        if (st == 1)
        {
            transform.position = spawn;
            cam.transform.position = spawn;
            canvas.SetActive(false);
            ccb.enabled = true;
        }

        if (st > 0) st--;
    }

    public void GoDead()
    {
        isDead = true;
        rb.gravityScale = 1;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        switch (collision.gameObject.tag)
        {
            case "Killer":
                GoDead();
                break;
        }
    }

    private void OnGUI()
    {
        if (speed != 1f)
        {
            GUILayout.TextField("speed: " + speed);
        }
    }
}
